<?php
class UserModel extends Model{ 
	
	//protected $fields = array ('usr_id','usr_name','usr_pw','usr_createtime','usr_timeout','usr_type','usr_property', '_autoinc' => true, '_pk' => 'usr_id', ); 
	
	private $property = array(
		'pay'	=>	1,#付费用户
		'order'	=>	2,#可以使用刷单工具
		'advSetting'=>4,#使用高级设置
		'checkIpLocation' => 8,#可以设置IP地址
		'checkIpRank'	=>16,#可以设置IP等级
	);
	
	/**
	 * @deprecated
	 * @param string $name 淘宝名称
	 * @return integer 用户ID
	 */
	function getUserId($name,$add=TRUE) {
		$user = $this->where(array(
			'usr_name' => $name,
		))->find();
		if ($user) {
			return $user;
		}elseif($add) {
			$todayReg = $this->where('usr_createtime>'.(time()-24*3600))->count();
			if ($todayReg<3) {
				$userInfo = array('usr_name'=>$name,'usr_createtime'=>time(),'usr_timeout'=>time()+1.5*24*3600,'usr_type'=>0);
				$id =  $this->add($userInfo);
				if ($id) {
					$userInfo['usr_id'] = $id;
					return $userInfo;
				}
			}
		}
	}
	
	/**
	 * 根据用户名，查找用户
	 * @param string $name 用户名
	 * @param boolean $add 如果没有找到，是否添加用户
	 * @return array
	 */
	function getUserByName($name,$add=FALSE) {
		$user = $this->where(array(
			'usr_name' => $name,
		))->find();
		if ($user) {
			return $user;
		}elseif($add) {
			$todayReg = $this->where('usr_createtime>'.(time()-24*3600))->count();
			if ($todayReg<3) {
				$userInfo = array('usr_name'=>$name,'usr_createtime'=>time(),'usr_timeout'=>time()+1.5*24*3600,'usr_type'=>0);
				$id =  $this->add($userInfo);
				if ($id) {
					$userInfo['usr_id'] = $id;
					return $userInfo;
				}
			}
		}
	}
	
	function encrypt($str) {
		return md5($str.md5('SSSSS___'));
	}
	
	/**
	 * 是否有标志位
	 * @param integer $property 标志位
	 * @param string $key 标志位字符
	 * @return boolean 是否有标志位
	 */
	function getProperty($property,$key) {
		return isset($this->property[$key]) && $this->property[$key]&$property;
	}

	function hasProperty($username,$key){
		$user = $this->getUserId($username,FALSE );
		if ( $user ) {
			return $this->getProperty($user['usr_property'],$key);
		}
		return false;
	}
	
	/**
	 * 续费
	 * @param int $usrId
	 * @param int $day
	 */
	function addTime($usrId,$day,$datetime) {
		$user = $this->find($usrId);
		$addTimeModel = D('Useraddtime');
		if ($user and !$addTimeModel->isAdded($usrId,$datetime)) {
			$user['usr_timeout'] = max($user['usr_timeout'],time()) + 3600*24*$day;
			$user['usr_property'] |= 1;
			$user['usr_type']	=	1;
			$addTimeModel->addTime($usrId,$day,$datetime);
			return $this->save($user);
		}
		return false;
	}
	
	/**
	 * 检查用户名
	 * @param string $username 用户名
	 * @return string|boolean 错误信息|成功true
	 */
	function checkName($username) {
		$username = trim($username);
		$notChar = array(
			'?' => '旺旺名不能出现“?”',
			'？'	=> '旺旺名不能出现“？”',
			' '	=>	'旺旺名不能出现空格',
		);
		foreach ($notChar as $char => $msg){
			if(FALSE!==stripos($username, $char)){
				return $msg;
			}
		}
		if (strlen($username)<3) {
			return '用户名必须大于2个字';
		}
		return TRUE;
	}
}
